package ar.fiuba.tp7552.buildadmin.util;

import java.io.File;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.cfg.Configuration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SchemaExport {
    
    public static void main(String args[]) throws Exception {
        if (args.length == 0) 
        	new SchemaExport().execute("target/schema.sql", false);
        else {
        	if (args.length > 1) {
        		new SchemaExport().execute("target/schema.sql", true);
        	} else {
        		new SchemaExport().execute(args[0], false);
        	}
        }
    }
    
    private void addAllFiles(File file, Configuration configuration) {
		if (file.isDirectory()) {
			for(File subfile : file.listFiles()) {
				addAllFiles(subfile, configuration);
			}
		} else {
			if (file.isFile() && file.getName().endsWith(".hbm.xml")) {
				configuration.addFile(file);
			}
		}
    }
    
    private void execute(String filename, boolean drop) throws Exception {
            
    	Properties prop = new Properties();
    	prop.load(this.getClass().getResourceAsStream("/app.properties"));
            
    	Configuration configuration = new Configuration();
    	configuration.setProperty("hibernate.dialect", prop.getProperty("hibernate.dialect"));
    	configuration.setNamingStrategy(new CustomNamingStrategy());
            
    	ClassLoader cl = SchemaExport.class.getClassLoader();
	
    	Enumeration<URL> en = cl.getResources(".");
    	while(en.hasMoreElements()) {
    		URL url = en.nextElement(); 
			File file = new File(url.toURI());
			addAllFiles(file, configuration);
    	}

    	org.hibernate.tool.hbm2ddl.SchemaExport object = null;
    	if (drop) {
    		ApplicationContext ctx =  new ClassPathXmlApplicationContext("classpath:spring/spring-persistence.xml");
    		DataSource datasurce = ctx.getBean("dataSource", DataSource.class);
    		object = new org.hibernate.tool.hbm2ddl.SchemaExport(configuration, datasurce.getConnection());
    		object.setDelimiter(";");
        	object.setFormat(false);
        	object.setOutputFile(filename);
        	object.execute(false, true, drop, !drop);
    	} else {
    		object = new org.hibernate.tool.hbm2ddl.SchemaExport(configuration);
    		object.setDelimiter(";");
        	object.setFormat(true);
        	object.setOutputFile(filename);
        	object.execute(true, false, drop, !drop);
    	}
    }
}